var $table;  
var selectionIds = [];  //保存选中ids  
var selectedIds = [];
var singleStatus = true;
var selectionList = []; //保存选中的实体对象集合
var sysUserField = dataObject.sysUserField;
var toolbar = "";
var isSelected = null;
var resourceId = null;
var userRole= false;
var companyNo = null; 
$(function () {
	  var columns =[
					{field: 'state', checkbox: true},
					{field: 'username' , title: sysUserField.username,formatter: 'nameFormatter', sortName:'USER_NAME' , sortable: true,halign: 'center',align: 'center'},
					{field: 'roleNames' , title: sysUserField.role, formatter: 'roleFormatter', halign: 'center',align: 'center'},
					{field: 'companyName' , title: sysUserField.companyNo, formatter: 'companyNameFormatter',sortName:'company_no' , sortable: true,halign: 'center',align: 'center'},
					{field: 'banLoginTime' , title: sysUserField.banLoginTime, sortName:'BAN_LOGIN_TIME' , sortable: true,halign: 'center',align: 'center'},
					{field: 'language' , title: sysUserField.language, sortName:'LANGUAGE' , sortable: true,halign: 'center',align: 'center'},
					{field: 'status' , title: sysUserField.status, formatter:'statusFormatter',sortName:'status' , sortable: true,halign: 'center',align: 'center'},
					{field: 'creator.username' , title: sysUserField.createBy, sortName:'CREATE_BY' , sortable: true,halign: 'center',align: 'center'},
					{field: 'createTime' , title: sysUserField.createTime, sortName:'create_time' , sortable: true,halign: 'center',align: 'center'},
			    	{field: 'action', title: pageData.action, formatter: '$table.actionFormatter', events: 'actionEvents', clickToSelect: false, width: 150, halign: 'center', align: 'center'}
		         ];
    $table = new BSTable("table", 'sys/sysuser/list', columns,"toolbar",560,'userId','user_id','sysuser');
    
    var queryParams = function(params) {            
         return {
         	  page: params.pageNumber,
         	  limit: params.pageSize,
         	  sidx: params.sortName,
              order: params.sortOrder,
              userId:vm.search.userId,     
              username:vm.search.username
              //查询字段
             };
     };
	$table.setQueryParams(queryParams);
    $table.init();
    
});

function companyNameFormatter(value,row){
    if(value == '运营中心'){
        return pageData.operationCenter;
    }
    if (row.companyNo) {
    	return '<a href="javascript:;" onclick="defaultActions.iframeDetail(\'详情\', \'../bus/buscompany.html?detailId='+ row.companyNo +'\');">'+value+'</a>';
	}
}
function roleFormatter(value,row){
    if(row.roleList && row.roleList instanceof Array){
    	var str = undefined;
    	$.each(row.roleList, function (i, n) {
    		if (!str) {
    			str = '<a href="javascript:;" onclick="defaultActions.iframeDetail(\'详情\', \'../sys/sysrole.html?detailId='+ n.roleId +'\', 550);">'+n.roleName+'</a>';
			} else {
    			str += ' <a href="javascript:;" onclick="defaultActions.iframeDetail(\'详情\', \'../sys/sysrole.html?detailId='+ n.roleId +'\', 550);">'+n.roleName+'</a>';
			}
        });
        return str;
    }
}

var vm = new Vue({
	el:'#app',
	data:{
		showList: true,
		title: null,
		passwordShow:true,
		roleList:[],
		sysUser: {	
			status:0,
			companyName:null,
			roleIdList:[],
			roleList:[]
		},
		isDetail: false,
		passMust:true,
		search:{
			id:null
		}
	},
	methods: {
		query: function () {
			//vm.search.isSearch = true;
			defaultActions.query();
		},
		add: function(){
			vm.isDetail = false;
			vm.passMust = true;
		    vm.sysUser={
					status:0,
					companyName:null,
					companyNo:null,
					roleIdList:[],
					roleList:[]
			};
			defaultActions.add(vm);
		},
		update: function (event, id) {
			vm.isDetail = false;
			vm.passMust = false;
		    defaultActions.update(id, $("#table"),$path+"/sys/sysuser/info/", vm, function(r){
	        	vm["sysUser"] = r["user"];
                selectionIds=[];
                selectionList=[];
                vm.sysUser.roleIdList = [];
                for(var i=0;i<vm.sysUser.roleList.length;i++){
                    vm.sysUser.roleIdList.push(vm.sysUser.roleList[i].roleId);
                    selectionList.push(vm.sysUser.roleList[i]);
                    selectionIds.push(vm.sysUser.roleList[i].roleId);
                }
	        });
		},
		saveOrUpdate: function (event) {
		    $('#defaultForm').bootstrapValidator('validate');
			if($('#defaultForm').data('bootstrapValidator').isValid()){
				if(vm.sysUser.password!=vm.sysUser.confirmPassword){
					alert("两次密码输入不一致");
					return
				}
				 if(vm.sysUser.roleIdList.length<=0){
				    	alert(sysUserField.role+pageData.notEmpty);
				    	return;
				 }
				 if((vm.sysUser.password == null || vm.sysUser.password == '') && vm.passMust){
					 alert(sysUserField.password+pageData.notEmpty);
					 return;
				 }
				 var url = (vm.sysUser.userId == null || vm.sysUser.userId == '') ?
                    $path+"/sys/sysuser/save" : $path+"/sys/sysuser/update";
				 defaultActions.saveOrUpdate(url ,vm, $("#defaultForm"),"sysUser",event);
			}
		},
		del: function (event, id) {
		    defaultActions.del(id, $path+"/sys/sysuser/delete", $("#table") ) ;
		},
		audit:function(status){
			defaultActions.audit(status , $path+"/sys/sysuser/audit/" + status, vm);
		},
		reload: function (event) {
		    defaultActions.reload($("#table"),$("#defaultForm"),vm,"sysUser"); 
		},
		detail: function (event, id) {
			defaultActions.detail(vm, id, event);
			vm.isDetail = true;
		},
		assiotRole: function(){
			selectionIds=[];
            selectionList=[];
			singleStatus = false;
		    $.each(vm.sysUser.roleIdList , function(i,data){
		    	selectionIds.push(data);
		    });
            $.each(vm.sysUser.roleList , function(i,data){
                selectionList.push(data);
            });
		    var fun = function(dialogRef) {
            	/*var row=$.map($("#table_dialog").bootstrapTable('getSelections'),function(row){
    				return row ;
    			});*/
            	vm.sysUser.roleIdList = [];
  			  	vm.sysUser.roleList = [];
    			for(var i=0;i<selectionList.length;i++){
    				vm.sysUser.roleIdList.push(selectionList[i].roleId);
    				vm.sysUser.roleList.push(selectionList[i]);
    				 vm.$nextTick(function () {
 	                    $('input[type=checkbox]').prop("disabled", true);
 	                    $('select').prop('disabled',true);
 	                })
    			}
    			dialogRef.close();
            };
		    defaultActions.assiot(pageData.assiot+sysUserField.role, '../dialog/sys/role_dialog.html', fun);
		},
		assiotCompany: function(){
			singleStatus = true;
			selectionIds=[];
            selectionList=[];
			selectionIds.push(vm.sysUser.companyNo);
			var fun = function(dialogRef) {
            	var row=$.map($("#table_dialog").bootstrapTable('getSelections'),function(row){
    				return row ;
    			});
            	var companyNo,companyName='';
    			for(var i=0;i<row.length;i++){
    				companyNo=row[i].companyNo;
    				companyName=row[i].companyName;
    			}
    			vm.sysUser.companyNo=companyNo;
				vm.sysUser.companyName=companyName;
				$("input[name='companyName']").val(vm.sysUser.companyName).change();
    			dialogRef.close();
            };
            defaultActions.assiot(pageData.assiot+sysUserField.companyNo, '../dialog/bus/busCompany_dialog.html', fun);
		}
	},
    /*updated: function () {
        this.$nextTick(function () {
        	if (vm.isDetail) {
                $('input[type=checkbox]').prop("disabled",true);
			}
        })
    }*/
});


/*表单校验 start*/
$('#defaultForm').bootstrapValidator({
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    excluded:[":disabled"],
    fields: {	    			    				
	    	username: {
	            message: 'The '+sysUserField.username+' is not valid',
	            validators: {
	                notEmpty: {
	                    message: sysUserField.username+pageData.notEmpty+'！'
	                },
	                stringLength: {
	                    max: 25,
	                    message: sysUserField.username+pageData.overLength+'25！'
	                },
	                regexp:{
	                	regexp : /^[\da-zA-Z@_.]+$/, 
	                	message: sysUserField.username+ pageData.supportType
	                },
	                remote: {
				        url: $path + '/sys/sysuser/checkRepeat',//验证地址
				        message: sysUserField.username + pageData.hasExists,//提示消息
				        delay :  500,//每输入一个字符，就发ajax请求，服务器压力还是太大，设置2秒发送一次ajax（默认输入一个字符，提交一次，服务器压力太大）
				        type: 'GET',//请求方式
				        dataType: "json",
				        data:{				        	
				        	username:function(){
				        		if(vm.sysUser.username == undefined){
				        			vm.sysUser.username = "";
	                			}
				        		return vm.sysUser.username;
				        	},
				        	userId:function(){
				        		if(vm.sysUser.userId == undefined){
				        			vm.sysUser.userId = "";
	                			}
				        		return vm.sysUser.userId;
				        	}
				        }  
				    }	                
	            }    
	        },
	    	    				
	    	password: {
	            message: 'The password is not valid',
	            validators: {
	                notEmpty: {
	                    message: sysUserField.password+pageData.notEmpty
	                },
	               regexp: {
                        regexp: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z0-9@_]{5,20}$/,
                        message: "密码长度（5-20），只能数字、字母、@和下划线，且必须包括至少一个数字、一个大写字母和一个小写字母",
                    }/*,
	                stringLength: {
	                    min: 5,
	                    max: 20,
	                    message: sysUserField.password + pageData.passwordLength
	                }*/
	            }
	        },
	    	
	        confirmPassword: {
	            message: 'The password is not valid',
	            validators: {
	                notEmpty: {
	                    message: sysUserField.password+pageData.notEmpty
	                },
	                identical:{
	                	field:'password',
	                	message: pageData.confirmPassword
	                }
	            }
	        },
	        email: vail.REGEXS("邮箱",sysUserField.email,/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/,"邮箱格式必须为X{n}@XX.X{n}"),
	        mobile: vail.REGEXS("联系方式",sysUserField.mobile,/^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/,"必须为11位手机号"),
	        companyName: {
	        	message: 'The '+sysUserField.companyNo+'  is not valid',
	        	trigger:"change",
	            validators: {
	                notEmpty: {
	                    message: sysUserField.companyNo+pageData.notEmpty
	                }
	            }	        	
	        },
	    	    		    
    }
});
/*表单校验 end*/

function resetOperBtn(){
    var deleteBtn=false;
    var auditSubmit = false;
    var auditPass = false;
    var auditNoPass = false;
    var updateBtn = false;
    var usedBtn = false;
    var stopBtn = false;
    var injectBtn = false;
    var uninjectBtn = false;
    var revoke = false;
    var pauseBtn = false;
    var rows = $("#table").bootstrapTable('getSelections');
    for (var i = 0; i < rows.length; i++) {
        var status;
        if(rows[i].status !== undefined && rows[i].status !== null){
            status = rows[i].status;
        }else{
            status = rows[i].auditStatus;
        }
        if(status==0){
            auditPass=true;
            auditNoPass=true;
            stopBtn = true;
            injectBtn = true;
            uninjectBtn = true;
            pauseBtn = true;
        }else if(status==1){
            updateBtn=true;
            deleteBtn=true;
            auditSubmit=true;
            injectBtn = true;
            uninjectBtn = true;
            pauseBtn = true;
            revoke = true;
        }else if(status==2){
            updateBtn=true;
            deleteBtn=true;
            auditSubmit=true;
            auditPass=true;
            uninjectBtn = true;
            revoke = true;

        }else if(status==3){
            auditPass=true;
            auditNoPass=true;
            injectBtn = true;
            uninjectBtn = true;
            pauseBtn = true;
        }else if (status == 4) {
            updateBtn=true;
            deleteBtn=true;
            auditSubmit=true;
            auditPass=true;
            auditNoPass=true;
            injectBtn = true;
            revoke = true;
        }else if (status == 5) {
            updateBtn=true;
            deleteBtn=true;
            auditSubmit=true;
            auditPass=true;
            uninjectBtn = true;
        }else if(status==6){
            //投放排期的暂停
            auditPass = true;
            auditNoPass = true;
            pauseBtn = true;
            deleteBtn=true;
        }else if(status==8){
            usedBtn = true;
            updateBtn=true;
            deleteBtn=true;
        }else if(status==9){
            stopBtn = true;
        }else if(status==10){
            deleteBtn=true;
            updateBtn=true;
        }else if(status==11){
            usedBtn = true;
            deleteBtn=true;
            updateBtn=true;
        }else if(status == 12){
            //注入中
            updateBtn=true;
            deleteBtn=true;
            auditSubmit=true;
            auditPass=true;
            auditNoPass=true;
            injectBtn = true;
            uninjectBtn = true;
        }else if(status == 13){
            //取消注入中
            updateBtn=true;
            deleteBtn=true;
            auditSubmit=true;
            auditPass=true;
            auditNoPass=true;
            injectBtn = true;
            uninjectBtn = true;
        }else if(status == 14){
            //注入失败
            updateBtn=true;
            deleteBtn=true;
            auditSubmit=true;
            auditPass=true;
            //auditNoPass=true;
            //injectBtn = true;
            uninjectBtn = true;
        }else if(status == 15){
            //取消注入失败
            updateBtn=true;
            deleteBtn=true;
            auditSubmit=true;
            auditPass=true;
            auditNoPass=true;
            injectBtn = true;
            //uninjectBtn = true;
        }
    }
    $("#update").attr("disabled",updateBtn);
    $("#delete").attr("disabled",deleteBtn);
    $("#submit").attr("disabled",auditSubmit);
    $("#checkOk").attr("disabled",auditPass);
    $("#auditpass").attr("disabled",auditPass);
    $("#checkFail").attr("disabled",auditNoPass);
    $("#auditnopass").attr("disabled",auditNoPass);
    $("#used").attr("disabled",usedBtn);
    $("#stopUsed").attr("disabled",stopBtn);
    $("#inject").attr("disabled",injectBtn);
    $("#uninject").attr("disabled",uninjectBtn);
    $("#revoke").attr("disabled", revoke);
    $("#pause").attr("disabled", pauseBtn);
}